package com.tiantianyuegou.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;

import com.tiantianyuegou.fragment.MemberFragment;
import com.tiantianyuegou.fragment.OneGouFragment;
import com.tiantianyuegou.model.UserInfoModel;
import com.tiantianyuegou.view.MyDialogTextView;
import com.tiantianyuegou.app.SysApplication;
import com.tiantianyuegou.fragment.CategoryFragment;
import com.tiantianyuegou.fragment.IndexFragment;
import com.tiantianyuegou.fragment.LocalShopFragment;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.Tools;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.http.ApiDefine;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 主界面
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {

    private boolean isFirstComing = true;

    List<Button> mButtons;
    private int currentTabIndex;
    private final Fragment[] mFragments = {new CategoryFragment(), new OneGouFragment(),
            new IndexFragment(), new MemberFragment()};
    private Button btn_shouye,btn_onegou, btn_fenlei,  btn_mine;
    private boolean isExit = false;//是否退出
    private TimerTask timeTask = null;
    private Timer timer;
    private LoadingDialog loadingDialog;

    Handler mHandler = null;
    private ChangeCityReceiver mChangeCityReceiver = new ChangeCityReceiver();

    //广播接收器，接收城市选择的item
    public class ChangeCityReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("TAG", intent.getStringExtra("cityName") + "reveive data");
            Message msg = Message.obtain();
            msg.obj = intent.getStringExtra("cityName");
            msg.what = 1;
            mHandler.sendMessage(msg);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Tools.changeSystemBar(this);
        initViews();

        // 创建一个新的非守护进程定时器
        timer = new Timer();

        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        if (savedInstanceState != null) {
            List<Fragment> fragments = getSupportFragmentManager()
                    .getFragments();
            for (Fragment f : fragments) {
                transaction.detach(f);
                transaction.remove(f);
            }
        }
        mButtons.get(0).setSelected(true);
        transaction.add(R.id.fragment_container, mFragments[0]).commit();

        //注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(CityListActivity.CITYSELECT);
        registerReceiver(mChangeCityReceiver, filter);
//        loadMember();
        SysApplication.getInstance().addActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadMember();
        String type = getIntent().getStringExtra("type");
        if (type != null) {
            getIntent().removeExtra("type");
            if ("order".equals(type)) {
                SysApplication.getInstance().addActivity(this);
                btn_mine.callOnClick();
            } else if ("exit".equals(type)) {
                SysApplication.getInstance().addActivity(this);
                btn_shouye.callOnClick();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mChangeCityReceiver);
    }

    @Override
    public void findViewByIds() {
        btn_shouye = (Button) findViewById(R.id.btn_shouye);
        btn_onegou = (Button) findViewById(R.id.btn_onegou);
        btn_fenlei = (Button) findViewById(R.id.btn_fenlei);

        btn_mine = (Button) findViewById(R.id.btn_mine);
        mButtons = new ArrayList<Button>();
        mButtons.add(btn_shouye);
        mButtons.add(btn_onegou);
        mButtons.add(btn_fenlei);
//        mButtons.add(btn_localshop);
//        mButtons.add(btn_tuangou);
        mButtons.add(btn_mine);
    }

    @Override
    public void initListener() {
        btn_shouye.setOnClickListener(this);
        btn_onegou.setOnClickListener(this);
        btn_fenlei.setOnClickListener(this);
//        btn_localshop.setOnClickListener(this);
//        btn_tuangou.setOnClickListener(this);
        btn_mine.setOnClickListener(this);
    }

    @Override
    public void initData() {
        checkOpenGPS();
    }

    public void setHandler(Handler handler) {
        mHandler = handler;
    }

    int index = currentTabIndex;

    public void onTabChange(View v) {
        switch (v.getId()) {
            case R.id.btn_shouye:
                index = 0;
                break;
            case R.id.btn_onegou:
                index = 1;
                break;
            case R.id.btn_fenlei:
                index = 2;
                break;

            case R.id.btn_mine:
                if ("".equals(SPHelper.getTmId()) || TextUtils.isEmpty(SPHelper.getTmId())) {
                    Intent btn_mine = new Intent();
                    btn_mine.setClass(MainActivity .this, LoginActivity.class);
                    btn_mine.putExtra("type", "mine");
                    startActivityForResult(btn_mine, 1002);
                    index = 3;

                } else {
                    index = 3;
                }


                break;
        }
        if (index == currentTabIndex)
            return;
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        transaction.hide(mFragments[currentTabIndex]);
        if (!mFragments[index].isAdded()) {
            transaction.add(R.id.fragment_container, mFragments[index]);
        }
        transaction.show(mFragments[index]).commit();
        mButtons.get(currentTabIndex).setSelected(false);
        mButtons.get(index).setSelected(true);
        currentTabIndex = index;
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (index == currentTabIndex)
            return;
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        transaction.hide(mFragments[currentTabIndex]);
        if (!mFragments[index].isAdded()) {
            transaction.add(R.id.fragment_container, mFragments[index]);
        }
        transaction.show(mFragments[index]).commit();
        mButtons.get(currentTabIndex).setSelected(false);
        mButtons.get(index).setSelected(true);
        currentTabIndex = index;
    }

    @Override
    public void onBackPressed() {
        if (isExit) {
            finish();
        } else {
            isExit = true;
            showMsg("再按一次退出");
            timeTask = new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            };
            timer.schedule(timeTask, 2000);
        }
    }

    private void loadMember() {


        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        Log.e("Main", "Main loadMember" + SPHelper.getTmId());
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.USER_INFO, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Log.e("MemberFragment", "onSuccess response.result  "
                        + responseInfo.result);
                String returnstr = responseInfo.result;

                try {
                    JSONObject json = new JSONObject(returnstr);
                    String code = json.getString("code");
                    Log.e("MemberFragment", json.getString("message"));

                    if (code.equals("100")) {
                        JSONObject jsonObject = json.getJSONObject("member");

//                        new UserInfoModel().setTmAvatar(jsonObject.getString("tmAvatar"));

                        SPHelper.setTmGuanCount(jsonObject.getString("tmGuanCount"));
                        SPHelper.setTmRedCount(jsonObject.getString("tmRedCount"));
                        Log.e("tag", "获取一些会员的数据");


                        // jsonObject.getString("");


                    } else {
                        Log.e("MemberFragment", "else code ！= 100");
                    }
                } catch (Exception e) {

                    e.printStackTrace();
                    Log.e("MemberFragment", "MemberFragment try catch" + e.toString());
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

                Log.e("TAG", "error" + s);
                Log.e("MemberFragment", "MemberFragment onFailure");

            }
        });
    }

    @Override
    public void onClick(View view) {
        onTabChange(view);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    private void checkOpenGPS() {
        LocationManager alm = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            return;
        }
        MyDialogTextView dialogTextView=new MyDialogTextView(this,"提示","确定开启GPS");
        dialogTextView.setDialogCallback(new MyDialogTextView.DialogCallback() {
            @Override
            public void dialogOpt() {
                Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
                startActivityForResult(intent, 0); //此为设置完成后返回到获取界面
            }
        });
        dialogTextView.show();
    }

}
